//
//  FolderViewController.m
//  Feeder
//
//  Created by Diego Acosta on 8/15/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FolderViewController.h"
#import "TDBadgedCell.h"
#import "GoogleReaderHelper.h"
#import "FeedItemsViewController.h"
#import "FormatHelper.h"

#define kTableSectionCount 1


@interface FolderViewController(Private)

- (NSString *)_getCurrentFeedId:(NSUInteger)index;
- (void)_setupBackButton;

@end


@implementation FolderViewController

@synthesize folder;
@synthesize folderprefs;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
	
    [super viewDidLoad];

	// format title.
	NSString * title = [FormatHelper stringFormatForTitle:[folder objectForKey:@"label"]
										  withUnreadCount:[folder objectForKey:@"count"]];
	
	// view title.
	self.navigationItem.title = title;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/

/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/

/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Private methods

- (NSString *)_getCurrentFeedId:(NSUInteger)index {

	// get all feeds for selected folder.
	NSDictionary * subs = [folder objectForKey:@"subscriptions"];
	NSString * _id;
	
	// we've to check if there's order preferences for this folder.
	if (folderprefs != nil) {
		
		// order subscription based on folder preferences.
		_id = [folderprefs objectAtIndex:index];
	}
	else {
		
		// we don't have user order preferences, go with the defaults.
		_id = [[subs allKeys] objectAtIndex:index];
	}
	
	return _id;
}

- (void)_setupBackButton {

	// override the navbar back button title to remove the unread items number.
	UIBarButtonItem * backButton = [[UIBarButtonItem alloc] initWithTitle:[folder objectForKey:@"label"]
																	style:UIBarButtonItemStyleBordered
																   target:nil
																   action:nil];
	
	[self.navigationItem setBackBarButtonItem:backButton];
	[backButton release];
}

#pragma mark -
#pragma mark UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	
    // Return the number of sections.
    return kTableSectionCount;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
    // Return the number of rows in the section.
    return [[folder objectForKey:@"subscriptions"] count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * CellIdentifier = @"BadgedCell";
	
	TDBadgedCell * cell = (TDBadgedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleDefault
										  reuseIdentifier:CellIdentifier] autorelease];
		
		// cell defaults.
		cell.badgeColor = [UIColor colorWithRed:140.0 / 255
										  green:153.0 / 255
										   blue:180.0 / 255
										  alpha:1.0];
		
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
	
	
	// we've to get the key for the user prefs if available, or just from the current
	// folder feed list.
	NSString * _id = [self _getCurrentFeedId:indexPath.row];
	
	// get all feeds for selected folder.
	NSDictionary * subs = [folder objectForKey:@"subscriptions"];
	
	// current feed to show.
	NSDictionary * sub = [subs objectForKey:_id];
	
	// customize cell.
	cell.textLabel.text = [sub objectForKey:@"title"];
	cell.badgeNumber = [sub objectForKey:@"count"];

	return (UITableViewCell *)cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark -
#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// get selected feed id.
	NSString * _id = [self _getCurrentFeedId:indexPath.row];
	
	// get all feeds for selected folder.
	NSDictionary * subs = [folder objectForKey:@"subscriptions"];
	
	// current feed to show.
	NSDictionary * sub = [subs objectForKey:_id];
	
	FeedItemsViewController * fivc = [[FeedItemsViewController alloc] initWithNibName:@"FeedItemsView"
																			   bundle:nil];
	
	// pass the feedid and data to the item list view.
	fivc.feedid = _id;
	fivc.feedinfo = sub;
	
	// remove unread-count from back button title.
	[self _setupBackButton];
	
	// push view.
	[self.navigationController pushViewController:fivc animated:YES];
	[fivc release];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc {
	
	[folder release];
	[folderprefs release];
    [super dealloc];
}

@end

